package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.mapper.CostomerReservationMapper;
import com.zzyl.service.CostomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import com.zzyl.vo.TimeCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CostomerReservationServiceImpI implements CostomerReservationService {
    @Autowired
    private CostomerReservationMapper costomerReservationMapper;
    //将时间戳转化为字符串
    private String convertTimeToStr(Long time){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time));

    }


//获取每个事件段的预约人数
    @Override
    public List<TimeCountVo> cotomerReservationCountByTime(LocalDateTime time) {
                     LocalDateTime   endTime = time.plusHours(24);
                    return costomerReservationMapper.countReservationsForEachTimeWithinTimeRange(time,endTime);

    }
//查询每个时间段剩余预约的次数
    @Override
    public int countReservation() {
        String name = UserThreadLocal.getSubject();
       int count = costomerReservationMapper.countReservation(name);
        return count;

    }

    @Override
    public void add(ReservationDto reservationDto) {

        //预约次数超过三次就不在进行预约了
        //否则就进行预约
        Reservation reservation=new Reservation();
        BeanUtils.copyProperties(reservationDto,reservation);
        reservation.setStatus(ReservationStatus.PENDING.getOrdinal());
        reservation.setCreateBy(UserThreadLocal.getUserId());
        reservation.setUpdateBy(UserThreadLocal.getUserId());
        reservation.setCreator(UserThreadLocal.getSubject());
        reservation.setUpdater(UserThreadLocal.getSubject());
        reservation.setName(UserThreadLocal.getSubject());
        reservation.setType(0);
        try {
            costomerReservationMapper.insert(reservation);
        } catch (Exception e) {
            log.info(e+"");
            throw new RuntimeException("此手机已经预约该时间");
        }

    }

    @Override
    public PageResponse<ReservationVo> getByPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Page<ReservationVo> page = costomerReservationMapper.getByPage(pageNum, pageSize, status);
        PageResponse<ReservationVo> pageResponse = new PageResponse<>(page);
        pageResponse.setRecords(page.getResult());
        return pageResponse;
    }

    @Override
    public void cancel(Long id) {
      costomerReservationMapper.cancel(id);
    }
}
